package src.base;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public abstract class LoadBalancer 
{
	public Vector<Element> loadbalancer_list;
	public ArrayList<Server> server_list;
	public int index_server;
	
	public LoadBalancer(int nb_server)
	{
		loadbalancer_list = new Vector<Element>();
		server_list = new ArrayList<Server>();
		index_server = 0;
		for (int i = 0; i < nb_server; i++)
		{
			server_list.add(new Server());
		}
	}
	
	public void push(Source src, int gauss_number)
	{
		//Get a part of the source between index and numberGauss
		List<Element> sublist = src.getSource().subList(src.getIndex(), src.getIndex() + gauss_number);
				
		//Add the sublist at the end of the actual list
		loadbalancer_list.addAll(sortIn(sublist));
		
		//Sort all the loadbalancer
		sort();
	}
	
	public List<Element> pull(int exp_number)
	{
		if (exp_number > loadbalancer_list.size()) exp_number = loadbalancer_list.size();
		Vector<Element> newlist = new Vector<Element>(loadbalancer_list);
		loadbalancer_list.subList(0, exp_number).clear();
		return sortOut(newlist.subList(0, exp_number));
	}
	
	public Vector<Element> getLoadBalancerList()
	{
		return loadbalancer_list;
	}
	
	public abstract void dispatch(List<Element> listout);
	
	/**
	 * Allow to sort Element inside the LoadBalancer
	 * return the results list
	 */
	public abstract void sort();
	
	/**
	 * Allow to sort Element when Element coming in the LoadBalancer
	 * return the results list
	 */
	public abstract List<Element> sortIn(List<Element> listin);
		
	/**
	 * Allow to sort Element when Element leaving the LoadBalancer
	 * return the results list
	 */
	public List<Element> sortOut(List<Element> listout)
	{
		return listout;
	}
	
	public List<Server> getServerList()
	{
		return server_list;
	}

	public void incIndexServer()
	{
		index_server = (index_server + 1) % server_list.size();
	}
	
	public String toString()
	{
		return "LB ("+ loadbalancer_list.size() +")";
	}
}
